package com.xafc.demo.security.utils;

import cn.hutool.core.map.MapUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Cookie操作工具类
 */
public class CookieUtils {

    public static int defaultCookieLife = 604800;

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
        addCookie(request, response, name, value, defaultCookieLife, false);
    }

    public static void addCookieByHttpOnly(HttpServletRequest request, HttpServletResponse response, String name, String value) {
        addCookie(request, response, name, value, defaultCookieLife, true);
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {
        addCookie(request, response, name, value, maxAge, false);
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        Cookie cookie = getCookieByName(request, name);
        if (null != cookie) {
            cookie.setMaxAge(0);
            cookie.setPath(request.getContextPath() + "/");
            response.addCookie(cookie);
        }
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge, boolean httpOnly) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(request.getContextPath() + "/");
        cookie.setHttpOnly(httpOnly);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        return cookieMap.containsKey(name) ? (Cookie)cookieMap.get(name) : null;
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        String cookieValue = "";
        Cookie c = getCookieByName(request, name);
        if (null != c) {
            cookieValue = c.getValue();
        }

        return cookieValue;
    }

    public static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = MapUtil.newHashMap();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                cookieMap.put(cookie.getName(), cookie);
            }
        }

        return cookieMap;
    }
}
